#include "stdafx.h"
#include "char_map.h"

char_map::char_map()
{
	m_head = new char_map_node("", "");
	m_tail = new char_map_node("", "");

	m_head->m_next = m_tail;
	m_tail->m_prev = m_head;

	m_count = 0;
}


char_map::~char_map()
{
	clear();

	delete m_head;
	delete m_tail;
	m_head = 0;
	m_tail = 0;

	m_count = 0;
}

int char_map::set(const char * key, const char * value)
{
	char_map_node* existed_node = find(key);
	if (existed_node)
	{
		existed_node->set_value(value);
	}
	else
	{
		char_map_node* new_node = new char_map_node(key, value);
		char_map_node* temp_node = m_tail->m_prev;
		m_tail->m_prev = new_node;
		temp_node->m_next = new_node;
		new_node->m_next = m_tail;
		new_node->m_prev = temp_node;
		m_count++;
	}

	return m_count;
}

void char_map::clear()
{
	while (m_head->m_next != m_tail)
	{
		char_map_node* del_node = m_tail->m_prev;
		char_map_node* temp_node = del_node->m_prev;
		temp_node->m_next = m_tail;
		m_tail->m_prev = temp_node;

		delete del_node;
	}
	m_count = 0;
}

const char * char_map::operator[](const char * key)
{
	char_map_node* temp_node = m_head->m_next;
	while (temp_node != m_tail)
	{
		if (!strcmp(temp_node->m_key, key))
		{
			return temp_node->m_value;
		}
		temp_node = temp_node->m_next;
	}
	return 0;
}

const char * char_map::get(int index)
{
	if (index < 0 || index >= get_count())
	{
		return 0;
	}

	int count = 0;
	char_map_node* temp_node = m_head->m_next;
	while (temp_node != m_tail)
	{
		if (count == index)
		{
			return temp_node->m_value;
		}
		temp_node = temp_node->m_next;
		count++;
	}
	return 0;
}

int char_map::get_count()
{
	return m_count;
}

char_map_node * char_map::find(const char * key)
{
	char_map_node* temp_node = m_head->m_next;
	while (temp_node != m_tail)
	{
		if (!strcmp(temp_node->m_key, key))
		{
			return temp_node;
		}
		temp_node = temp_node->m_next;
	}
	return 0;
}

void char_map::show()
{
	char_map_node* temp_node = m_head->m_next;

	while (temp_node != m_tail)
	{
		cout << temp_node->m_key << ":" << temp_node->m_value << ",";
		temp_node = temp_node->m_next;
	}

	cout << endl;

	temp_node = m_tail->m_prev;
	while (temp_node != m_head)
	{
		cout << temp_node->m_key << ":" << temp_node->m_value << ",";
		temp_node = temp_node->m_prev;
	}
}


